package cn.xyz.mianshi.utils;

import cn.xyz.commons.autoconfigure.KApplicationProperties.SmsConfig;
import cn.xyz.commons.utils.DateUtil;
import cn.xyz.commons.utils.HttpClientUtil;
import cn.xyz.commons.utils.WebNetEncode;
import cn.xyz.mianshi.vo.SmsRecord;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;

import com.aliyuncs.ecs.model.v20140526.DescribeInstancesRequest;
import com.aliyuncs.ecs.model.v20140526.DescribeInstancesResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/** @version:（1.0） 
* @ClassName	SMSPushUtils
* @Description: （短信验证服务） 
* @date:2018年9月8日下午12:20:30  
*/ 
@Component
public class SMSVerificationUtils {
	
	protected static Logger smsLogger=LoggerFactory.getLogger("SMSVerificationUtils");
	
	public static SmsConfig getSmsConfig() {
		return SKBeanUtils.getSmsConfig();
	}

	public static final String SMSFORMAT = "00";
	
	public static boolean sendSms(String telephone, String code, String areaCode) throws ClientException {
		// 可自助调整超时时间
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		boolean isSuccess = false;
		 DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",getSmsConfig().getAccesskeyid(),
					getSmsConfig().getAccesskeysecret());
		 
		  IAcsClient client = new DefaultAcsClient(profile);

	        CommonRequest request = new CommonRequest();
	        request.setSysMethod(MethodType.POST);
	        request.setSysDomain("dysmsapi.ap-southeast-1.aliyuncs.com");
	        request.setSysVersion("2018-05-01");
	        if(areaCode.equals("86") ||areaCode.equals("1") )
	        {
	        	request.setSysAction("SendMessageWithTemplate");
	        	request.putQueryParameter("TemplateCode", "SMS_11265055");
	        	request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
	        	request.putQueryParameter("From", getSmsConfig().getSignname());
	        }
	        else {
	        	request.setSysAction("SendMessageToGlobe");
	        	request.putQueryParameter("Message", "[yestalk]Your verification code:"+code);
	        }
	      
	        
	        request.putQueryParameter("To",telephone);
	        request.putQueryParameter("RegionId", "ap-southeast-1");
	        
	        
	      
	        try {
	        	CommonResponse response = client.getCommonResponse(request);
	        	JSONObject _obj = JSON.parseObject(response.getData());
	        	if(_obj.getString("ResponseCode").equals("OK"))
	        	{
	        		isSuccess = true;
	        	}
	        	
	            System.out.println(response.getData());
	        } catch (ServerException e) {
	            e.printStackTrace();
	        } catch (ClientException e) {
	            e.printStackTrace();
	        }
		return isSuccess;
	}

	// 使用天天国际短信平台发送国际短信
	public static String sendSmsToMs360(String telephone, String areaCode, String code) {
		String msgId = null;
		try {
			String ip = getSmsConfig().getHost();
			int port = getSmsConfig().getPort();
			// HTTP 请求工具
			HttpClientUtil util = new HttpClientUtil(ip, port, getSmsConfig().getApi());
			String user = getSmsConfig().getUsername();// 你的用户名
			String pwd = getSmsConfig().getPassword();// 你的密码：
			String ServiceID = "SEND"; // 固定，不需要改变
			String dest = telephone; // 你的目的号码【收短信的电话号码】
			String sender = "";// 你的原号码,可空【大部分国家原号码带不过去，只有少数国家支持透传，所有一般为空】
			String templateEnglishSMS = new String(getSmsConfig().getTemplateEnglishSMS().getBytes("ISO-8859-1"),"utf-8");
			String msg = templateEnglishSMS + code;// 你的短信内容
			if ("86".equals(areaCode) || "886".equals(areaCode) || "852".equals(areaCode)) {
				String templateChineseSMS = new String(getSmsConfig().getTemplateChineseSMS().getBytes("ISO-8859-1"),"utf-8");
				msg = templateChineseSMS + code;
				
			}
			// codec=8 Unicode 编码, 3 ISO-8859-1, 0 ASCII
			// 短信内容 HEX 编码，8 为 UTF-16BE HEX 编码， dataCoding = 8 ,支持所有国家的语言，建议直接使用
			// 8
			String hex = WebNetEncode.encodeHexStr(8, msg);
			hex = hex.trim() + "&codec=8";
			// HTTP 封包请求, util.sendPostMessage 返回结果，
			// 如果是以 “-” 开头的为发送失败，请查看错误代码，否则为MSGID
			msgId = util.sendGetMessage(user, pwd, ServiceID, dest, sender, hex);
			smsLogger.info("msgid =  " + msgId + "    msg = " + msg);
			// 发送短信记录保存到数据库
			saveSMSToDB(telephone, areaCode, code, msg, msgId);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return msgId;
	}
	//使用短信宝发送国内短信
	public  static  String sendSmsTosmsBao(String telephone, String areaCode, String code)
	{

		Map params = new HashMap();//请求参数
		String smsBaoUserName = getSmsConfig().getSmsBaoUserName();
		String smsBaoPassWord = getSmsConfig().getSmsBaoPassWord();
		String smsContent = getSmsConfig().getSmsBaoChinase_templetecode();
		String smsUrl = getSmsConfig().getSmsBaoUrl();
		if(!areaCode.equals("86"))
		{
			smsUrl = getSmsConfig().getSmsBaoNetUrl();
			smsContent  = getSmsConfig().getSmsBaoChinase_templetecodeNet();
			telephone = "+"+areaCode+telephone;

		}
		try{
			telephone =  java.net.URLEncoder.encode(telephone,"UTF-8");
			smsContent =  java.net.URLEncoder.encode(String.format(smsContent,code),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		params.put("u",smsBaoUserName);
		params.put("p",smsBaoPassWord);
		params.put("m",telephone);
		params.put("c",smsContent);
		String szResult = "";
		try {
			szResult = HttpClientUtil.sendGetMessage(smsUrl,params,"GET");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return szResult;
	}
		// 使用聚合发送国内短信
		public static String sendSmsToJvHe(String telephone, String areaCode, String code) {
			String msgId = null;
			try {
				String tpl_id = getSmsConfig().getJvheId();
				String APPKEY =  getSmsConfig().getJvheKey();
				Map params = new HashMap();//请求参数
				int areaCodeLen = areaCode.length();
				telephone = telephone.substring(areaCodeLen);
	            params.put("mobile",telephone);//接收短信的手机号码
	            params.put("tpl_id",tpl_id);//短信模板ID，请参考个人中心短信模板设置
	            params.put("tpl_value","#code#="+code);//变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，<a href="http://www.juhe.cn/news/index/id/50" target="_blank">详细说明></a>
	            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
	          
				
				msgId = HttpClientUtil.sendGetMessage("http://v.juhe.cn/sms/send",params,"GET");
				smsLogger.info("sendSmsToJvHe msgid =  " + msgId+",telephone="+telephone);
				
				// 发送短信记录保存到数据库
				saveSMSToDB(telephone, areaCode, code, code, msgId);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return msgId;
		}
		// 使用聚合发送国际短信
		public static String sendSmsToJvHeNet(String telephone, String areaCode, String code)
		{
			String msgId = null;
			try {
				String tpl_id = getSmsConfig().getJvheIdNet();
				String APPKEY =  getSmsConfig().getJvheKeyNet();
				Map params = new HashMap();//请求参数
				int areaCodeLen = areaCode.length();
				telephone = telephone.substring(areaCodeLen);
				params.put("areaNum",areaCode);//接收短信的手机号码
	            params.put("mobile",telephone);//接收短信的手机号码
	            params.put("tplId",tpl_id);//短信模板ID，请参考个人中心短信模板设置
	            params.put("tplValue","#code#="+code);//变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，<a href="http://www.juhe.cn/news/index/id/50" target="_blank">详细说明></a>
	            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
	          
				
				msgId = HttpClientUtil.sendGetMessage("http://v.juhe.cn/smsInternational/send.php",params,"GET");
				smsLogger.info("sendSmsToJvHe msgid =  " + msgId+",telephone="+telephone);
				
				// 发送短信记录保存到数据库
				saveSMSToDB(telephone, areaCode, code, code, msgId);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return msgId;
		}

	/**
	 * @Description:（短信详情存库）
	 * @param telephone
	 * @param areaCode
	 * @param code
	 * @param content
	 * @param msgId
	 **/
	public static void saveSMSToDB(String telephone, String areaCode, String code, String content, String msgId) {
		SmsRecord sms = ConstantUtil.getSmsPrice(areaCode);
		if (null == sms)
			sms = new SmsRecord();
		sms.setAreaCode(areaCode);
		sms.setTelephone(telephone);
		sms.setCode(code);
		sms.setContent(content);
		sms.setMsgId(msgId);
		sms.setTime(DateUtil.currentTimeSeconds());
		ConstantUtil.dsForRW.save(sms);
	}
}
